package com.itheima.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.commons.utils.Constants;
import com.itheima.dubbo.api.*;
import com.itheima.model.domain.User;
import com.itheima.model.domain.UserInfo;
import com.itheima.model.mongo.Comment;
import com.itheima.model.mongo.Video;
import com.itheima.model.vo.CountsVo;
import com.itheima.model.vo.PageResult;
import com.itheima.model.vo.UserDataVo;
import com.itheima.model.vo.UserVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.itheima.autoconfig.template.HuanXinTemplate;
import com.itheima.model.mongo.Movement;
import com.itheima.model.vo.*;
import com.itheima.tanhua.admin.exception.BusinessException;
import org.bson.types.ObjectId;
import java.util.HashMap;

/**
 * @author zhangpei
 * @ClassName ManagedService
 * @date 2022/6/21/13:55
 */
@Service
public class ManageService {
    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;


    @DubboReference
    private UserInfoApi userinfoApi;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private CommentsApi commentsApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 后台用户管理 分页列表
     */
    public PageResult users(Integer page, Integer pagesize, Long id, String nickname, String city) {
        Page<UserInfo> iPage = userInfoApi.users(page, pagesize, id, nickname, city);
        //拿到分页后的数据列表
        List<UserInfo> userInfoList = iPage.getRecords();
        //获得所有用户Id查用户
        List<Long> ids = CollUtil.getFieldValues(userInfoList, "id", Long.class);
        Map<Long, User> userMap = userApi.findByIds(ids);
        Map<Long, UserInfo> userInfoMap = CollUtil.fieldValueMap(userInfoList, "id");
        //转为UserDataVo对象
        ArrayList<UserDataVo> userDataVos = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            if (userInfo != null) {
                if (userInfo.getUserStatus() == "2") {
                    String value = redisTemplate.opsForValue().get(Constants.USER_FREEZE_KEY + userInfo.getId());
                    if (StringUtils.isEmpty(value)) {
                        userInfo.setUserStatus("1");
                        userInfoApi.update(userInfo);
                    }
                }
                UserDataVo userDataVo = UserDataVo.init(userInfoMap.get(userInfo.getId()), userMap.get(userInfo.getId()));
                userDataVos.add(userDataVo);
            }
        }
        return new PageResult(page, pagesize, iPage.getTotal(), userDataVos);
    }

    @DubboReference
    private UserLikeApi userLikeApi;

    /**
     * 用户基本数据
     */
    public UserVo baseInfo(Long userID) {
        UserInfo userInfo = userInfoApi.findById(userID);
        User user = userApi.findById(userID);
        CountsVo counts = userLikeApi.counts(userID);
        UserVo userVo = UserVo.init(userInfo, user, counts);
        return userVo;
    }

    /**
     * 冻结用户
     */
    public boolean freeze(Map map) {
        try {
            Long userId = Long.valueOf(map.get("userId").toString());
            Integer freezingTime = Integer.valueOf(map.get("freezingTime").toString());
            Integer freezingRange = Integer.valueOf(map.get("freezingRange").toString());
            String reasonsForFreezing = map.get("reasonsForFreezing").toString();
            String frozenRemarks = map.get("frozenRemarks").toString();
            //冻结时间
            int days = 0;
            if (freezingTime == 1) {
                days = 3;
            }
            if (freezingTime == 2) {
                days = 7;
            }
            if (freezingTime == 3) {
                days = 999999999;
            }
            //冻结范围
            String scope = "";
            if (freezingTime == 1) {
                scope = "冻结登录";
            }
            if (freezingTime == 2) {
                scope = "冻结发言";
            }
            if (freezingTime == 3) {
                scope = "冻结发布动态";
            }
            //往redis里存入标记
            redisTemplate.opsForValue().set(Constants.USER_FREEZE_KEY + userId, scope, Duration.ofDays(days));
            //更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(userId);
            userInfo.setUserStatus("2");
            //更新状态
            userInfoApi.update(userInfo);
            return true;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 用户解冻
     */
    public boolean unfreeze(Map map) {
        try {
            Long userId = Long.valueOf(map.get("userId").toString());
            String reasonsForThawing = map.get("reasonsForThawing").toString();
            redisTemplate.delete(Constants.USER_FREEZE_KEY + userId);
            UserInfo userInfo = userInfoApi.findById(userId);
            userInfo.setUserStatus("1");
            userInfoApi.update(userInfo);
            return true;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return false;
        }
    }
    @DubboReference
    public FriendApi friendApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private MovementApi movementApi;




    public Map<String, String> pass(String[] item) {

        //接受字符串数组 根据 ，切割
        ArrayList<Long> objectIds = new ArrayList<>();
        for (String s : item) {
            Long aLong = Long.valueOf(s);
            objectIds.add(aLong);
        }
        //修改对应id的state字段为3
        //调用方法
        Map<String,String> map = movementApi.pass(objectIds);
        if (map == null){
             throw new BusinessException(ErrorResult.error());
        }
        //得到返回值  {"message":"adipisicing pariatur Ut"}   map
        return map;
    }

    public Map<String, String> reject(String[] item) {
        //接受字符串数组 根据 ，切割
        ArrayList<Long> objectIds = new ArrayList<>();
        for (String s : item) {
            Long aLong = Long.valueOf(s);
            objectIds.add(aLong);
        }
        //修改对应id的state字段为3
        //调用方法
        Map<String,String> map = movementApi.reject(objectIds);
        if (map == null){
            throw new BusinessException(ErrorResult.error());
        }
        //得到返回值  {"message":"adipisicing pariatur Ut"}   map
        return map;
    }

    public Map<String, String> revocation(String[] item) {
        //接受字符串数组 根据 ，切割
        ArrayList<Long> objectIds = new ArrayList<>();
        for (String s : item) {
            Long aLong = Long.valueOf(s);
            objectIds.add(aLong);
        }
        //修改对应id的state字段为3
        //调用方法
        Map<String,String> map = movementApi.revocation(objectIds);
        if (map == null){
            throw new BusinessException(ErrorResult.error());
        }
        //得到返回值  {"message":"adipisicing pariatur Ut"}   map
        return map;
    }

    //获得详情
    public MovementsHVo messages(Integer id) {
        //根据ID 获得moven
        Movement movement = movementApi.findById(id.toString());
        //再根据movment获得userid
        movement.getUserId();


        UserInfo byid = userinfoApi.findById(movement.getUserId());

        MovementsHVo init = MovementsHVo.init(byid, movement);
        //从redis获得置顶数据
        String key = Constants.MOVEMENTS_INTERACT_KEY;
        String hashKey = Constants.MOVEMENT_ZD + id;
        Object o = redisTemplate.opsForHash().get(key, hashKey);
        if (o != null){
            init.setTopState(2);
        }
        return init;
    }

    //消息置顶
    public Map<String, String> top(Integer id) {
        //直接在redis中保存这个数据
        String key = Constants.MOVEMENTS_INTERACT_KEY;
        String hashKey = Constants.MOVEMENT_ZD + id;
        redisTemplate.opsForHash().put(key, hashKey,"1");

        Map<String,String> map = new HashMap<>();
        map.put("message","操作成功");
        return map;
    }

    public Map<String, String> untop(Integer id) {
        //直接在redis中保存这个数据
        String key = Constants.MOVEMENTS_INTERACT_KEY;
        String hashKey = Constants.MOVEMENT_ZD + id;
        redisTemplate.opsForHash().delete(key, hashKey);

        Map<String,String> map = new HashMap<>();
        map.put("message","操作成功");
        return map;
    }

    //分页查询
    public PageResultM getmeassagelist(int page, int pagesize, String sortProp, String sortOrder, String id, Long sd, Long ed, Integer state, String lx,Long uid) {
        //传入参数 进行查询得到 分页数据
        //根据传入的东西 查询所需要的字段
        ArrayList<Total> totals = new ArrayList<>();

        if (lx == "Messages"){
            //统计里面的所有数据
            Total total = new Total();
            total.setTitle("全部");
            total.setCode("1");
            //统计所有动态数量
            ArrayList<Integer> ids = new ArrayList<>();
            ids.add(1);
            ids.add(2);
            ids.add(3);
            ids.add(4);
            ids.add(5);
            ids.add(6);
            Long countall = movementApi.count(ids);
            total.setValue(countall);
            totals.add(total);

            //待审核
            Total total1 = new Total();
            total1.setTitle("待审核");
            total1.setCode("2");
            //统计所有动态数量
            ArrayList<Integer> ids1 = new ArrayList<>();
            ids1.add(3);
            Long countall1 = movementApi.count(ids1);
            total1.setValue(countall1);
            totals.add(total1);

            //已通过
            Total total2 = new Total();
            total2.setTitle("已通过");
            total2.setCode("3");
            //统计所有动态数量
            ArrayList<Integer> ids2 = new ArrayList<>();
            ids2.add(5);
            Long countall2 = movementApi.count(ids2);
            total2.setValue(countall2);
            totals.add(total2);

            //已拒绝
            Total total3 = new Total();
            total3.setTitle("已拒绝");
            total3.setCode("4");
            //统计所有动态数量
            ArrayList<Integer> ids3 = new ArrayList<>();
            ids3.add(4);

            Long countall3 = movementApi.count(ids3);
            total3.setValue(countall3);
            totals.add(total3);



        }

        //得到分野数据
        List<Movement> movements = movementApi.getmassage(page,pagesize,sortProp,sortOrder,id,sd,ed,state,uid);
        if (movements == null) {
           return new PageResultM(page,pagesize,0,new ArrayList<>(),totals);
        }
        //提取id
        List<Long> userIds = CollUtil.getFieldValues(movements, "userId", Long.class);
        if (userIds.size() == 0){
            return new PageResultM(page,pagesize,0,new ArrayList<>(),totals);
        }
        //获得userinfo
        Map<Long, UserInfo> map = userinfoApi.findByIds(userIds,null);
        ArrayList<MovementsHVo> movementsHVos = new ArrayList<>();
        //如果请求是已通过的 要改变sata 为 5
        for (Movement movement : movements) {
            //
            UserInfo userInfo = map.get(movement.getUserId());
            if (userInfo != null){
                MovementsHVo init = MovementsHVo.init(userInfo, movement);
                movementsHVos.add(init);
            }

        }

        //后面还有 但是我不想写了
        return new PageResultM(page,pagesize,0,movementsHVos,totals);
    }

    public PageResult getmeassagelists(int page, int pagesize, String sortProp, String sortOrderInteger,Long uid) {
        List<Movement> llist = movementApi.getlist(page,pagesize,sortProp,sortOrderInteger,uid);
        return new PageResult(page,pagesize,0l,llist);
    }


    public PageResult videos(Long uid, Integer page, Integer pagesize, String sortProp, String sortOrder) {
        List<Video> list = videoApi.findById(uid, page, pagesize);
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, User> byIds = userApi.findByIds(userIds);
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds,null );
        List<VideosDto> videoVoList = new ArrayList<>();
        for (Video video : list) {
            VideosDto VideosDto = new VideosDto();
            UserInfo userInfo = userInfoMap.get(video.getUserId());
            com.itheima.model.vo.VideosDto videosDto = VideosDto.init(userInfo, Integer.valueOf(uid.toString()), video);
            /*VideosDto.setCreateDate(video.getCreated());*/
            videoVoList.add(videosDto);
        }

        Long count = videoApi.count(uid);
        ArrayList<Vo> vos = new ArrayList<>();
        Long typeCount1 = videoApi.countType(1);
        Vo vo1 = new Vo();
        vo1.setCode("1");
        vo1.setTitle("全部");
        vo1.setValue(typeCount1.intValue());

        Long typeCount2 = videoApi.countType(2);
        Vo vo2 = new Vo();
        vo2.setCode("2");
        vo2.setTitle("待审核");
        vo2.setValue(typeCount1.intValue());

        Long typeCount3 = videoApi.countType(3);
        Vo vo3 = new Vo();
        vo3.setCode("3");
        vo3.setTitle("已通过");
        vo3.setValue(typeCount1.intValue());

        Long typeCount4 = videoApi.countType(4);
        Vo vo4 = new Vo();
        vo4.setCode("4");
        vo4.setTitle("已拒绝");
        vo4.setValue(typeCount1.intValue());
        vos.add(vo1);
        vos.add(vo2);
        vos.add(vo3);
        vos.add(vo4);

        PageResult pageResult = new PageResult(page, pagesize, count, videoVoList);
        pageResult.setTotals(vos);
        return pageResult;
    }


    public PageResult comments(Long messageID, Integer page, Integer pagesize, String sortProp, String sortOrder) {

        List<Comment> llist = commentsApi.getlist(page,pagesize,sortProp,sortOrder,messageID);
        return new PageResult(page,pagesize,0l,llist);
    }
}
